#!/usr/bin/env bash
set -e
configFile="vite.config.ts"
name=$(cat package.json | grep -m 1 '\"name\"' | awk -F '\"' '{print $4}')
projectPath=$PWD
nodeVersion=18.14.0
run="yarn dev"

help() {
  cat <<EOF

HELP：
-f 强制重新运行
-l 进入log
-h 显示帮助
-c 指定config文件(获取port)
-n node版本号
-r 启动命令 eg: yarn dev
--name 镜像名称(放最后)

EOF
}

while getopts ":c:n:r:-:fhl" opt; do
  case $opt in
  c)
    configFile="$OPTARG"
    ;;
  f)
    isForce=true
    ;;
  h)
    help
    exit 1
    ;;
  l)
    isLog=true
    ;;
  n)
    nodeVersion="$OPTARG"
    ;;
  r)
    run="$OPTARG"
    ;;
  -)
    case "${OPTARG}" in
    name)
      name=${!OPTIND}
      ;;
    help)
      help
      exit 1
      ;;
    *)
      echo "$OPTARG"
      ;;
    esac
    ;;
  \?)
    echo "Invalid option: -$OPTARG" >&2
    exit 1
    ;;
  :)
    echo "Option -$OPTARG requires an argument." >&2
    exit 1
    ;;
  esac
done

port=$(cat $configFile | grep -m 1 'port:' | awk -F ':' '{print $2}' | tr -cd "[0-9]")
if [ -z "$name" ]; then
  echo "未有name"
  help
  exit 1
fi
if [ -z "$port" ]; then
  echo "未有port"
  exit 1
fi
# echo "-f 强制重新运行"
if [[ "$isForce" == true ]]; then
  if docker ps -a --format '{{.Names}}' | grep -q $name; then
    docker stop $name
    docker rm $name
  fi
fi

if docker ps --format '{{.Names}}' | grep -q $name; then
  echo "${name}已经在运行!"
elif docker ps -a --format '{{.Names}}' | grep -q $name; then
  echo "正在运行!"
  docker start $name
else
  docker run --name $name -p $port:$port -v ~/nodeCache:/root/nodeCache -v $projectPath:/root/d -t -d node:$nodeVersion-alpine sh -c "cd ~/d && yarn config set registry https://registry.npmmirror.com && yarn config set cache-folder /root/nodeCache/.yarn && yarn && $run"
fi

if [[ "$isLog" == true ]]; then
  docker logs -f $name
fi
